package com.maltys.backtracking;

import java.util.ArrayList;
import java.util.List;

/**
 * @author malty
 * @link <a href="https://leetcode.cn/problems/permutations/description//">全排列</a>
 */
public class Permutations {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        backTracing(nums, new int[nums.length], new ArrayList<>(), res);
        return res;
    }

    private void backTracing(int[] nums, int[] used, List<Integer> list, List<List<Integer>> res) {
        if (list.size() == nums.length) {
            res.add(new ArrayList<>(list));
        }

        for (int i = 0; i < nums.length; i++) {
            if (used[i] == 1) {
                continue;
            }
            used[i] = 1;
            list.add(nums[i]);
            backTracing(nums, used, list, res);
            used[i] = 0;
            list.remove(list.size() - 1);
        }
    }

    public static void main(String[] args) {
        Permutations permutations = new Permutations();
        List<List<Integer>> permute = permutations.permute(new int[]{1, 2, 3});
        permute.forEach(System.out::println);
    }
}
